package sf.database.jdbc.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Types;

public class StringSQLXMLType implements TypeHandler<String> {
    public String get(ResultSet rs, String colName) throws SQLException {
        return sqlxmlToString(rs.getSQLXML(colName));
    }

    public String get(ResultSet rs, int index) throws SQLException {
        return sqlxmlToString(rs.getSQLXML(index));
    }

    public String get(CallableStatement rs, int index) throws SQLException {
        return sqlxmlToString(rs.getSQLXML(index));
    }

    @Override
    public String get(CallableStatement cs, String parameterName) throws SQLException {
        return sqlxmlToString(cs.getSQLXML(parameterName));
    }

    @Override
    public void update(ResultSet rs, String columnLabel, Object value) throws SQLException {
        SQLXML xml = rs.getStatement().getConnection().createSQLXML();
        try {
            xml.setString(String.valueOf(value));
            rs.updateSQLXML(columnLabel, xml);
        } finally {
            xml.free();
        }
    }

    @Override
    public void update(ResultSet rs, int columnIndex, Object value) throws SQLException {
        SQLXML xml = rs.getStatement().getConnection().createSQLXML();
        try {
            xml.setString(String.valueOf(value));
            rs.updateSQLXML(columnIndex, xml);
        } finally {
            xml.free();
        }
    }

    public Object set(PreparedStatement stat, Object obj, int index) throws SQLException {
        if (null == obj) {
            stat.setNull(index, getSqlType());
        } else {
            SQLXML xml = stat.getConnection().createSQLXML();
            try {
                xml.setString(String.valueOf(obj));
                stat.setSQLXML(index, xml);
            } finally {
                xml.free();
            }
        }
        return null;
    }

    @Override
    public Object set(CallableStatement cs, Object obj, String parameterName) throws SQLException {
        if (null == obj) {
            cs.setNull(parameterName, getSqlType());
        } else {
            SQLXML xml = cs.getConnection().createSQLXML();
            try {
                xml.setString(String.valueOf(obj));
                cs.setSQLXML(parameterName, xml);
            } finally {
                xml.free();
            }
        }
        return null;
    }

    protected String sqlxmlToString(SQLXML sqlxml) throws SQLException {
        if (sqlxml == null) {
            return null;
        }
        try {
            return sqlxml.getString();
        } finally {
            sqlxml.free();
        }
    }

    @Override
    public int getSqlType() {
        return Types.SQLXML;
    }

    @Override
    public Class<String> getDefaultJavaType() {
        return String.class;
    }
}
